<template>
  <div>
    <el-upload
      list-type="picture-card"
      :limit="1"
      action="#"
      :on-preview="preview"
      :file-list="fileList"
      :class="{ disabled: fileComputed }"
      :on-remove="handleRemove"
      :on-change="changeFile"
      :before-upload="beforeUpload"
      :http-request="upload"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-progress v-if="showPercent" style="width:180px" :percentage="percent" />
    <el-dialog title="图片" :visible.sync="showDialog">
      <img :src="imgUrl" style="width:100%" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5' // 引入腾讯云sdk
const cos = new COS({
  SecretId: 'AKIDd191cwzlHWUAajaAUXJo2zf4C3dwznKb',
  SecretKey: '1lEQM1PWMuCDxQcXBYeT1II2VhbEbgU1'
})
export default {
  name: '',
  components: {},
  props: {},
  data() {
    return {
      fileList: [],
      showDialog: false,
      imgUrl: '',
      currentFileUid: '',
      percent: 0,
      showPercent: false
    }
  },
  computed: {
    fileComputed() {
      return this.fileList.length === 1
    }
  },
  watch: {},
  created() {},
  mounted() {},
  methods: {
    // 预览
    preview(file) {
      this.imgUrl = file.url
      this.showDialog = true
    },
    // 删除
    handleRemove(file) {
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
      console.log(file)
    },
    // 修改文件时触发
    changeFile(file, fileList) {
      this.fileList = fileList.map(item => item)
    },
    // 上传之前的检查
    beforeUpload(file) {
      const types = ['image/jpeg', 'image/gif', 'img/bmp', 'image/png']
      // 检查文件类型
      if (!types.includes(file.type)) {
        this.$message.error('上传图片只能是JPG,GIF,BMP,PNG格式')
        return false
      }
      // 检查大小
      const maxSize = 5 * 1024 * 1024
      if (maxSize < file.size) {
        this.$message.error('图片大小最大不能超过5m')
        return false
      }
      // 已经确定当前上传的就是当前的这个file了
      this.currentFileUid = file.uid
      this.showPercent = true
      return true
    },
    // 自定义上传动作
    upload(params) {
      // console.log(params.file)
      if (params.file) {
        // 执行上传操作
        cos.putObject(
          {
            Bucket: 'xiaofenfen-1306938762', // 存储桶
            Region: 'ap-chengdu',
            Key: 'params.file.name',
            Body: params.file,
            StorageClass: 'STANDARD',
            // 进度条
            onProgress: params => {
              this.percent = params.percent * 100
            }
          },
          (err, data) => {
            console.log(err || data)
            // 当data中有一个statusCode===200的时候说明上传成功
            if (!err && data.statusCode === 200) {
              // 此时说明文件上传成功，要获取成功的返回地址
              // fileList才能显示到上传组件上，此时我们要将fileList中的数据的url变成现在上传成功的
              this.fileList = this.fileList.map(item => {
                // 去找谁的uid等于刚记录下来的uid
                if (item.uid === this.currentFileUid) {
                  // 将成功的地址赋值给原来的url属性
                  return { url: 'http://' + data.Location, upload: true }
                }
                return item
              })
              setTimeout(() => {
                this.showPercent = false
                this.percent = 0
              }, 2000)
            }
          }
        )
      }
    }
  }
}
</script>

<style>
.disabled .el-upload--picture-card {
  display: none;
}
</style>
